<script setup lang="ts">
import baseTable from '@/components/base-ui/base-table/index.vue';
import MateriaCode from '@/views/Demand/Order/dialog/materiaCode/index.vue';
import CustomerInfo from '@/views/Demand/Order/dialog/customerInfo/index.vue';
import usePageSave from '@/hooks/usePageSave';
import useEmit from '@/hooks/useEmitter';
import { tableConfig } from './config/table-config';
import { Message } from '@/instance';
import { doAddOrder } from '@/api/demand/order/index';
import { handleDelKey, checkRepeat, RepeatMsg } from '@/utils';
import { protoSubmitData } from '../../type';
import type { MaterialChooseVO } from '@/api/modeling/ProcessManagement/model/type';
import type { CustomerInformationListInfo } from '@/api/base/customerInformation/model/type';

const { modalOk, modalSlotRef, loading } = useModal();

defineOptions({
    name: 'OrderAdd'
});

const STORE_KEY = 'orderAddData'; // store数据的key
const { startRecording, isUpdate } = useEmit(STORE_KEY); // 页面标签路由关闭二次确认事件监听 EventBus

useRecordData(modalSlotRef, STORE_KEY, isUpdate, startRecording); // 复制订单相关

/**
 * 校验相关
 */
const { resetRelatedValid } = useValid();

/**
 * @: 提交
 */
const handleSubmit = async () => {
    const value = modalSlotRef.value?.getSaveData();
    const params = value.map((item: protoSubmitData) => {
        return handleDelKey(item, ['id', 'unAction', 'itemName']);
    });
    const msg = checkRepeat(value, ['orderNumber']);
    if (msg) {
        const { line, value } = msg;
        RepeatMsg({ line, value, label: '订单号' });
        return;
    }
    try {
        const res = await doAddOrder(params);
        if (res) {
            Message.success('新增订单成功！');
            return res;
        }
    } catch (error) {
        console.log(error);
    }
};

/**
 * 选择物料编码
 */
const selectMaterialCode = ref<string>(); // 选择的物料Id
const validMateriaId = ref(); // 校验Id
const tableIndex = ref(0); // 校验索引
const materiaVisible = ref(false);
const handleMateria = (row: anyObj, id: number | string, index: number = 0) => {
    selectMaterialCode.value = row.itemCode;
    validMateriaId.value = id;
    tableIndex.value = index;
    materiaVisible.value = true;
};

/**
 * 选择物料编码，点击保存
 */
const handleMaterialCodeOk = (materialData: MaterialChooseVO) => {
    resetRelatedValid([validMateriaId.value], tableIndex.value);

    // 过滤出当前所选的 id 项
    const currentRow = modalSlotRef.value.tableData[tableIndex.value];
    currentRow.itemCode = materialData.materialCode;
    currentRow.itemName = materialData.materialName;
};

/**
 * 选择客户信息
 */
const selectCustomerCode = ref<string>(); // 选择的客户Id
const validCustomerId = ref(); // 校验Id
const tableCustomerIndex = ref(0); // 校验索引
const customerVisible = ref(false);
const handleCustomerInfo = (row: anyObj, id: number | string, index: number = 0) => {
    selectCustomerCode.value = row.customerCode;
    validCustomerId.value = id;
    tableCustomerIndex.value = index;
    customerVisible.value = true;
};

/**
 * 选择客户编码，点击保存
 */
const handleCustomerCodeOk = (customerData: CustomerInformationListInfo) => {
    resetRelatedValid([validCustomerId.value], tableCustomerIndex.value);

    // 过滤出当前所选的 id 项
    const currentRow = modalSlotRef.value.tableData[tableCustomerIndex.value];
    currentRow.customerCode = customerData.customerCode;
    currentRow.customerCompanyName = customerData.customerName;
};

/**
 * @: 点击保存
 */
const handleOk = async () => {
    try {
        await modalOk(handleSubmit);
        usePageSave('/Demand');
    } catch (e) {
        console.log(e);
    }
};
</script>
<template>
    <q-page>
        <base-table
            ref="modalSlotRef"
            :table-config="tableConfig"
            show-fullscreen
            add-table-row
            open-sticky
        >
            <!-- 保存/取消 -->
            <template #tableHeadEnd>
                <q-submit-button
                    size="default"
                    :hide-label="true"
                    align="right"
                    :horizontal="true"
                    :loading="loading"
                    :cancel-button="false"
                    @save="handleOk"
                />
            </template>

            <!-- 物料编码下拉框 -->
            <template #itemCode="{ row, item, index }">
                <q-virtual-select
                    v-model="row.itemCode"
                    placeholder="请选择"
                    @click="handleMateria(row, item.validProps?.id!, index)"
                    @clear="row.itemName = ''"
                />
            </template>

            <!-- 客户编码下拉框 -->
            <template #customerCode="{ row, item, index }">
                <q-virtual-select
                    v-model="row.customerCode"
                    placeholder="请选择"
                    @click="handleCustomerInfo(row, item.validProps?.id!, index)"
                    @clear="row.customerCompanyName = ''"
                />
            </template>
        </base-table>

        <!-- 物料编码 -->
        <MateriaCode
            v-model:visible="materiaVisible"
            :code="selectMaterialCode"
            @ok="handleMaterialCodeOk"
        />

        <!-- 客户编码 -->
        <CustomerInfo
            v-model:visible="customerVisible"
            :code="selectCustomerCode"
            @ok="handleCustomerCodeOk"
        />
    </q-page>
</template>

<style lang="scss" scoped></style>
